package cn.mayaslight.wechat.utils;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.mayaslight.common.utils.JsonUtil;

public class HttpUtil {
	
	public static final String XML_HTTP_REQUEST = "XMLHttpRequest";
	
	public static void printText(HttpServletResponse response, String text) throws IOException{
		printText(response, text, false);
	}
	
	public static void printText(HttpServletResponse response, String text, boolean isClosed) throws IOException{
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print(text);
		out.flush();
		if(isClosed){
			out.close();
		}
	}

	public static void printBody(HttpServletResponse response, Object obj) throws IOException{
		printBody(response, obj, false);
	}
	
	public static void printBody(HttpServletResponse response, Object obj, boolean isClosed) throws IOException{
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print(JsonUtil.toJSONString(obj));
		out.flush();
		if(isClosed){
			out.close();
		}
	}
	
	public static boolean hasXRequestWith(HttpServletRequest request) {
		String xRequestWith = request.getHeader("x-requested-with");
		if(!org.springframework.util.StringUtils.isEmpty(xRequestWith) && XML_HTTP_REQUEST.equals(xRequestWith)){
			return true; 
		}else{
			return false;
		}
	}
	
	public static String getReqURL(HttpServletRequest request){
		String contextPath = request.getContextPath();
		String uri = request.getRequestURI();
		StringBuffer newUrl = new StringBuffer();
		if(uri.indexOf(contextPath) > -1){
			newUrl.append(uri.substring(0, uri.indexOf(contextPath))).append(uri.substring(uri.indexOf(contextPath) + contextPath.length(), uri.length()));
			return newUrl.toString();
		}else
			return uri;
	}
	
}
